package cn.com.infcn.maven;

import cn.com.infcn.Task.TimerTask;
import cn.com.infcn.util.ConfigUtils;
import cn.com.infcn.util.HttpUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by cc on 2016/12/26.
 *
 * @author jijs
 */
@WebServlet(name = "MavenRepositoryServlet", urlPatterns = "/maven/*")
public class MavenRepositoryServlet extends HttpServlet {


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext ctx = this.getServletContext();
        try {
            String pathInfo = request.getPathInfo();
//            System.out.println("请求路径：pathInfo==========" + pathInfo);

            //获取Maven本地仓库路径
            String localRepository = ConfigUtils.getLocalRepository(ctx);

            assert localRepository != null;
            File f = new File(localRepository);
            File[] list = f.listFiles();

            File file = null;
            boolean flag = false;

            if (list != null) {
                for (File t : list) {
                    if(t.isDirectory()){
                        //获取请求文件路径
                        String filePath = localRepository + File.separator + t.getName() + pathInfo.replace("/", File.separator);
                        file = new File(filePath);

                        if (file.exists()) {
                            flag = true;
                            break;
                        }else{
                            file = null;
                        }
                    }
                }
            }

            //判断本地文件是否存在，如果则输出
            if (flag) {
                responseStream(response, file);
            } else {

                String remoteRepositoryUrl = ConfigUtils.getRemoteRepositoryUrl(ctx);
                final String remoteRepositoryFileUrl = remoteRepositoryUrl + pathInfo;

                HttpUtils.sendGet(remoteRepositoryFileUrl, response);
            }



        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


    //响应请求的文件
    private void responseStream(HttpServletResponse response, File file) {

        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            response.setHeader("Content-Type", "application/octet-stream");

            int len;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void init() throws ServletException {
        ServletContext ctx = this.getServletContext();
        //初始化参数
        ConfigUtils.getProperties(ctx);
        TimerTask.execute();
    }
}
